<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:price_extend="{row}">
      <input type="hidden" :name="row.name" :value="price_extend_encode(row.value)">
      <p v-for="(v,i) in row.value" style="line-height: 1.6;padding: 02px;">
        <span>{{v.num}}个月：￥{{v.price}}</span>
        <el-button size="small" type="danger" @click="row.value.splice(i,1)">删除</el-button>
      </p>
      <json_param :config="json_param_config" v-model:value="price_extend_row"></json_param>
      <el-button @click="add_price_extend" size="small">添加</el-button>
    </template>
  </forms>
</template>

<script>
import json_param from "@/components/auto_import/UnifyParam/json_param.vue";
import {ajax} from "@/js/api_tool.js";
import {iframe, in_right_admin} from "@/js/tool.js";
import s94Mjs from "s94-js";

export default {
  props: ['__iframe'],
  components: {json_param},
  data(){
    let id = this.$get('id'), btns = undefined;
    //管理员部分
    let rights_init = 'Admin/*,AdminLog/*,AdminRole/*,Config/*';
    //用户管理部分
    rights_init += ',User/*,UserComment/*,UserMoneyLog/*,UserMoneyRecharge/*,UserRealName/*,UserWithdraw/*,Agent/*,AgentApply/*';
    //营销部分
    rights_init += ',UserLevel/*,UserKickback/*,KickbackRatio/*,KickbackType/*,MessageTemplate/*,Code/*,CodeGroup/*,Promotion/*,SpecialObject/*';
    //内容部分
    rights_init += ',Content/*,Link/*,Category/*,Count/*,Additional/*,SkuGroup/*';
    //订单部分
    rights_init += ',OrderRefund/*,OrderSharing/*,SharingReceiver/*';
    //系统管理部分
    rights_init += ',File/*,FileCategory/*,Event/*,IndexCard/*,MessageReply/*,Param/*,WechatArticle/*,WechatMenu/*';
    let forms_config = {
      title: {label:'标题',name:'title',type:'text_one',tips:''},
      info: {label:'简介',name:'info',type:'text_more',tips:''},
      price: {label:'价格',name:'price',type:'text_one',config:'number',tips:'单价(每个月)'},
      price_extend: {label:'价格扩展',name:'price_extend',type:'price_extend',tips:'',value:[]},
      content: {label:'介绍',name:'content',type:'editor',tips:''},
      rights: {label:'权限选择',name:'rights',type:'checkbox',config:[],tips:'',value:rights_init},
    }
    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      json_param_config: {
        num: {label:'时长(月)',name:'num',type:'text_one',config:'number',tips:''},
        price: {label:'价格',name:'price',type:'text_one',config:'number',tips:''},
      },
      price_extend_row: '{}',
    }
  },
  methods: {
    onsubmit(formData){
      let row = JSON.parse(this.price_extend_row);
      if (row.num || row.price){
        this.$confirm('存在未添加的价格扩展，如果提交，未添加的价格扩展会被舍弃，是否舍弃', '操作确定').then(()=>{
          this.price_extend_row = '{}';
          this.send(formData);
        }).catch(()=>{})
      }else {
        this.send(formData);
      }
    },
    send(formData){
      let url = this.id ? `/admin/tenant_package/edit?id=`+this.id : '/admin/tenant_package/add';
      // formData.set('rights', this.encode_rights(formData.get('rights')) );
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('tenant_package/index', '$refs.list_url.list');
          iframe.hide('tenant_package/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    price_extend_encode(arr){
      let obj = {};
      let unit = 3600*24*30;
      s94Mjs.each(arr, function (v){
        obj[unit*v.num] = v.price;
      })
      return JSON.stringify(obj);
    },
    price_extend_decode(str){
      let one_moon = 3600*24*30;
      let res = [];
      s94Mjs.each(str ? JSON.parse(str) : [], function (v,k){
        res.push({num: Math.round(k/one_moon), price: v})
      })
      return res;
    },
    add_price_extend(callback){
      let app = this;
      callback = typeof(callback) =='function' ? callback : function (){app.$message.error('添加完成');}
      let row = JSON.parse(app.price_extend_row);
      let old_data = app.config.price_extend.value;
      if (row.price <= 0) return app.$message.error('设定的价格必须大于0！');
      if (row.num <= 0 || row.num != Math.round(row.num)) return app.$message.error('设定的时长(月)必须大于0，并且为整数');
      for (let i = 0; i < old_data.length; i++) {
        if (old_data[i].num == row.num) return app.$message.error('设定的时长(月)不能重复');
      }
      app.config.price_extend.value.push(row);
      app.price_extend_row = '{}';
    },
    encode_rights(rights_value){
      let app = this, rights = [], all = true;
      rights_value  = rights_value ? rights_value.split(',') : [];
      s94Mjs.each(app.config.rights.config, function(row, c) {
        let vals = [],row_all = true;
        s94Mjs.each(row.children, function(row){
          if (~rights_value.indexOf(row.value)){
            vals.push(row.value);
          }else {
            row_all = false;
          }
        })
        if(row_all){
          rights.push(row.value)
        }else{
          all = false;
          rights = rights.concat(vals);
        }
      });
      return all?'*/*':rights.join(',');
    },
    decode_rights(rights_value){
      let app = this, rights = [];
      if (!Object.values(app.config.rights.config).length) return rights_value;
      rights_value  = rights_value ? rights_value.split(',') : [];
      s94Mjs.eachloop(app.config.rights.config, 'children', function(row){
        if (in_right_admin(row.value, rights_value)) rights.push(row.value);
        return true;
      })
      return rights.join(',');
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/tenant_package/info?id='+this.id, cache:true}, (res)=>{
        // res.data.rights = this.decode_rights(res.data.rights);
        res.data.price_extend = app.price_extend_decode(res.data.price_extend);
        this.$refs['forms'].init(res.data);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('tenant_package/edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
    ajax({url:'/admin/admin_role/rights?is_tenant=1', cache:true},(res)=>{
        this.config.rights.config = res.data;
        return false
    })
  }
}
</script>
